package com.intelligent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.mapper.*;
import com.intelligent.pojo.*;
import com.intelligent.service.SupplierReconciliationDetailService;
import com.intelligent.vo.SupplierReconciliationDetailPageReq;
import com.intelligent.vo.SupplierReconciliationDetailResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author HP
* @description 针对表【supplier_reconciliation_detail(供应商对账明细表)】的数据库操作Service实现
* @createDate 2025-08-28 19:18:19
*/
@Service
public class SupplierReconciliationDetailServiceImpl extends ServiceImpl<SupplierReconciliationDetailMapper, SupplierReconciliationDetail>
    implements SupplierReconciliationDetailService{

    @Autowired
    private SupplierReconciliationMapper reconciliationMapper;

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    @Autowired
    private PaymentOrderMapper paymentOrderMapper;

    @Autowired
    private WarehouseReceiptMapper warehouseReceiptMapper;

    @Autowired
    private PurchaseSupplierMapper purchaseSupplierMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Page<SupplierReconciliationDetailResp> pageDetails(SupplierReconciliationDetailPageReq req) {
        System.out.println("开始分页查询，请求参数: " + req);
        
        // 构建查询条件
        Page<SupplierReconciliationDetail> entityPage = new Page<>(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<SupplierReconciliationDetail> dw = new LambdaQueryWrapper<>();

        // 根据对账单号查找对应的对账单ID
        if (req.getReconciliationNo() != null && !req.getReconciliationNo().trim().isEmpty()) {
            LambdaQueryWrapper<SupplierReconciliation> rcw = new LambdaQueryWrapper<>();
            rcw.like(SupplierReconciliation::getReconciliationNo, req.getReconciliationNo().trim());
            if (req.getSupplierId() != null) {
                rcw.eq(SupplierReconciliation::getSupplierId, req.getSupplierId());
            }
            List<SupplierReconciliation> recos = reconciliationMapper.selectList(rcw);
            if (recos.isEmpty()) {
                System.out.println("未找到对账单号: " + req.getReconciliationNo());
                return empty(req);
            }
            List<Long> recoIds = recos.stream().map(SupplierReconciliation::getId).collect(Collectors.toList());
            dw.in(SupplierReconciliationDetail::getReconciliationId, recoIds);
            System.out.println("找到对账单ID列表: " + recoIds);
        }

        if (req.getPurchaseOrderId() != null) {
            dw.eq(SupplierReconciliationDetail::getPurchaseOrderId, req.getPurchaseOrderId());
        }

        if (req.getPaymentOrderId() != null) {
            dw.eq(SupplierReconciliationDetail::getPaymentOrderId, req.getPaymentOrderId());
        }

        if (req.getGoodsReceiptId() != null) {
            dw.eq(SupplierReconciliationDetail::getGoodsReceiptId, req.getGoodsReceiptId());
        }

        dw.orderByDesc(SupplierReconciliationDetail::getId);
        this.page(entityPage, dw);
        
        System.out.println("查询到明细记录数量: " + entityPage.getRecords().size());

        if (entityPage.getRecords().isEmpty()) {
            return empty(req);
        }

        // 构建响应数据
        List<SupplierReconciliationDetailResp> rows = entityPage.getRecords().stream()
                .map(this::buildDetail)
                .collect(Collectors.toList());

        Page<SupplierReconciliationDetailResp> vo = new Page<>(entityPage.getCurrent(), entityPage.getSize(), entityPage.getTotal());
        vo.setRecords(rows);
        
        System.out.println("返回响应记录数量: " + rows.size());
        return vo;
    }

    @Override
    public SupplierReconciliationDetailResp getDetail(Long id) {
        System.out.println("=== 开始获取明细详情，ID: " + id + " ===");
        SupplierReconciliationDetail d = this.getById(id);
        if (d == null) {
            System.out.println("未找到明细记录，ID: " + id);
            return null;
        }
        System.out.println("找到明细记录: " + d);
        SupplierReconciliationDetailResp resp = buildDetail(d);
        System.out.println("=== 详情获取完成，返回响应: " + resp + " ===");
        return resp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void generateFromReconciliation(Long reconciliationId) {
        // 获取供应商对账单信息
        SupplierReconciliation reconciliation = reconciliationMapper.selectById(reconciliationId);
        if (reconciliation == null) {
            throw new RuntimeException("对账单不存在");
        }

        Long supplierId = reconciliation.getSupplierId();
        if (supplierId == null) {
            throw new RuntimeException("对账单缺少供应商信息");
        }

        Date startDate = reconciliation.getCreateTime();
        Date endDate = new Date(); // 使用当前时间作为结束时间，或者可以根据业务需求调整

        // 查询该供应商的所有采购订单（暂时不限制时间范围）
        LambdaQueryWrapper<PurchaseOrder> orderWrapper = new LambdaQueryWrapper<>();
        orderWrapper.eq(PurchaseOrder::getSupplierId, supplierId);
        // 暂时注释掉时间范围限制，先确保能查询到数据
        // if (startDate != null) {
        //     orderWrapper.ge(PurchaseOrder::getExpectedStorageTime, startDate);
        // }
        // if (endDate != null) {
        //     orderWrapper.le(PurchaseOrder::getExpectedStorageTime, endDate);
        // }
        List<PurchaseOrder> purchaseOrders = purchaseOrderMapper.selectList(orderWrapper);

        if (purchaseOrders.isEmpty()) {
            // 添加调试信息
            System.out.println("供应商ID: " + supplierId + " 没有找到采购订单");
            return; // 没有采购订单，直接返回
        }

        System.out.println("找到采购订单数量: " + purchaseOrders.size());

        List<SupplierReconciliationDetail> batch = new ArrayList<>();

        for (PurchaseOrder purchaseOrder : purchaseOrders) {
            System.out.println("处理采购订单: " + purchaseOrder.getOrderNo() + ", ID: " + purchaseOrder.getId());

            // 查询相关的收货单
            LambdaQueryWrapper<WarehouseReceipt> receiptWrapper = new LambdaQueryWrapper<>();
            receiptWrapper.eq(WarehouseReceipt::getOrderId, purchaseOrder.getId());
            // 暂时不限制入库类型，先确保能查询到数据
            // .eq(WarehouseReceipt::getReceiptType, 1); // 采购入库类型
            List<WarehouseReceipt> receipts = warehouseReceiptMapper.selectList(receiptWrapper);

            System.out.println("采购订单 " + purchaseOrder.getOrderNo() + " 的收货单数量: " + receipts.size());
            
            // 如果没有找到收货单，尝试查询所有收货单看看数据结构
            if (receipts.isEmpty()) {
                System.out.println("没有找到收货单，查询所有收货单数据:");
                List<WarehouseReceipt> allReceipts = warehouseReceiptMapper.selectList(null);
                System.out.println("数据库中总收货单数量: " + allReceipts.size());
                for (WarehouseReceipt r : allReceipts) {
                    System.out.println("收货单: ID=" + r.getId() + ", 订单ID=" + r.getOrderId() + ", 收货单号=" + r.getReceiptNo());
                }
            }

            // 查询相关的付款单（根据采购订单号关联）
            LambdaQueryWrapper<PaymentOrder> paymentWrapper = new LambdaQueryWrapper<>();
            paymentWrapper.eq(PaymentOrder::getRelatedSalesOrder, purchaseOrder.getOrderNo());
            // 暂时不限制付款类型，先确保能查询到数据
            // .eq(PaymentOrder::getPaymentType, "1"); // 采购付款类型
            List<PaymentOrder> payments = paymentOrderMapper.selectList(paymentWrapper);

            System.out.println("采购订单 " + purchaseOrder.getOrderNo() + " 的付款单数量: " + payments.size());

            // 为每个采购订单创建明细记录
            for (WarehouseReceipt receipt : receipts) {
                // 检查是否已存在该明细记录
                LambdaQueryWrapper<SupplierReconciliationDetail> existWrapper = new LambdaQueryWrapper<>();
                existWrapper.eq(SupplierReconciliationDetail::getReconciliationId, reconciliationId)
                           .eq(SupplierReconciliationDetail::getPurchaseOrderId, purchaseOrder.getId())
                           .eq(SupplierReconciliationDetail::getGoodsReceiptId, receipt.getId().intValue());

                if (this.count(existWrapper) > 0) {
                    System.out.println("明细记录已存在，跳过: reconciliationId=" + reconciliationId + ", purchaseOrderId=" + purchaseOrder.getId() + ", goodsReceiptId=" + receipt.getId());
                    continue; // 已存在，跳过
                }

                SupplierReconciliationDetail detail = new SupplierReconciliationDetail();
                detail.setReconciliationId(reconciliationId);
                detail.setPurchaseOrderId(purchaseOrder.getId());
                detail.setGoodsReceiptId(receipt.getId().intValue());

                // 如果有相关的付款单，关联第一个
                if (!payments.isEmpty()) {
                    detail.setPaymentOrderId(payments.get(0).getId());
                }

                batch.add(detail);
                System.out.println("添加明细记录: " + detail);
            }

            // 如果没有收货单，也可以创建只有采购订单的明细记录
            if (receipts.isEmpty()) {
                // 检查是否已存在该明细记录
                LambdaQueryWrapper<SupplierReconciliationDetail> existWrapper = new LambdaQueryWrapper<>();
                existWrapper.eq(SupplierReconciliationDetail::getReconciliationId, reconciliationId)
                           .eq(SupplierReconciliationDetail::getPurchaseOrderId, purchaseOrder.getId())
                           .isNull(SupplierReconciliationDetail::getGoodsReceiptId);

                if (this.count(existWrapper) == 0) {
                    SupplierReconciliationDetail detail = new SupplierReconciliationDetail();
                    detail.setReconciliationId(reconciliationId);
                    detail.setPurchaseOrderId(purchaseOrder.getId());

                    // 如果有相关的付款单，关联第一个
                    if (!payments.isEmpty()) {
                        detail.setPaymentOrderId(payments.get(0).getId());
                    }

                    batch.add(detail);
                    System.out.println("添加只有采购订单的明细记录: " + detail);
                } else {
                    System.out.println("只有采购订单的明细记录已存在，跳过: reconciliationId=" + reconciliationId + ", purchaseOrderId=" + purchaseOrder.getId());
                }
            }
        }

        System.out.println("准备保存的明细记录数量: " + batch.size());
        if (!batch.isEmpty()) {
            boolean saveResult = this.saveBatch(batch);
            System.out.println("批量保存结果: " + saveResult);
        } else {
            System.out.println("没有需要保存的明细记录");
        }
    }

    private Page<SupplierReconciliationDetailResp> empty(SupplierReconciliationDetailPageReq req) {
        Page<SupplierReconciliationDetailResp> vo = new Page<>(req.getPageNum(), req.getPageSize(), 0L);
        vo.setRecords(Collections.emptyList());
        return vo;
    }

    private SupplierReconciliationDetailResp buildDetail(SupplierReconciliationDetail d) {
        System.out.println("开始构建明细响应，明细ID: " + d.getId() + ", 对账单ID: " + d.getReconciliationId() + ", 采购订单ID: " + d.getPurchaseOrderId() + ", 付款单ID: " + d.getPaymentOrderId() + ", 收货单ID: " + d.getGoodsReceiptId());
        
        SupplierReconciliationDetailResp resp = new SupplierReconciliationDetailResp();
        resp.setId(d.getId());
        resp.setReconciliationId(d.getReconciliationId());
        resp.setPurchaseOrderId(d.getPurchaseOrderId());
        resp.setGoodsReceiptId(d.getGoodsReceiptId());
        resp.setPaymentOrderId(d.getPaymentOrderId());

        // 设置对账单信息
        if (d.getReconciliationId() != null) {
            SupplierReconciliation reco = reconciliationMapper.selectById(d.getReconciliationId());
            if (reco != null) {
                resp.setReconciliationNo(reco.getReconciliationNo());
                resp.setSupplierId(reco.getSupplierId());

                // 设置供应商信息
                if (reco.getSupplierId() != null) {
                    PurchaseSupplier supplier = purchaseSupplierMapper.selectById(reco.getSupplierId());
                    if (supplier != null) {
                        resp.setSupplierName(supplier.getSupplierName());
                    }
                }
            }
        }

        // 设置采购订单信息
        if (d.getPurchaseOrderId() != null) {
            PurchaseOrder purchaseOrder = purchaseOrderMapper.selectById(d.getPurchaseOrderId());
            if (purchaseOrder != null) {
                resp.setPurchaseOrderNo(purchaseOrder.getOrderNo());
                resp.setPurchaseAmount(purchaseOrder.getPurchaseAmount());
                resp.setPurchaseQuantity(purchaseOrder.getPurchaseQuantity());
                resp.setExpectedStorageTime(purchaseOrder.getExpectedStorageTime());
                System.out.println("采购订单信息: " + purchaseOrder.getOrderNo() + ", 采购金额: " + purchaseOrder.getPurchaseAmount() + ", 采购数量: " + purchaseOrder.getPurchaseQuantity());
            } else {
                System.out.println("未找到采购订单ID: " + d.getPurchaseOrderId());
            }
        } else {
            System.out.println("采购订单ID为空");
        }

        // 设置付款单信息
        if (d.getPaymentOrderId() != null) {
            PaymentOrder paymentOrder = paymentOrderMapper.selectById(d.getPaymentOrderId());
            if (paymentOrder != null) {
                resp.setPaymentOrderNo(paymentOrder.getPaymentOrderNo());
                resp.setPayableAmount(paymentOrder.getPayableAmount());
                resp.setWrittenOffAmount(paymentOrder.getWrittenOffAmount());
                // 暂时注释掉，因为数据库可能没有这个字段
                // resp.setAmountWrittenOff(paymentOrder.getAmountWrittenOff());
                resp.setPaymentDate(paymentOrder.getCreationDate());
                System.out.println("付款单信息: " + paymentOrder.getPaymentOrderNo() + ", 应付金额: " + paymentOrder.getPayableAmount() + ", 已核销金额: " + paymentOrder.getWrittenOffAmount());
            } else {
                System.out.println("未找到付款单ID: " + d.getPaymentOrderId());
            }
        } else {
            System.out.println("付款单ID为空");
        }

        // 设置收货单信息
        if (d.getGoodsReceiptId() != null) {
            WarehouseReceipt receipt = warehouseReceiptMapper.selectById(d.getGoodsReceiptId().longValue());
            if (receipt != null) {
                resp.setReceiptNo(receipt.getReceiptNo());
                resp.setReceiptTime(receipt.getReceiptTime());
                resp.setProductCount(receipt.getProductCount());
                System.out.println("收货单信息: " + receipt.getReceiptNo() + ", 收货时间: " + receipt.getReceiptTime() + ", 产品数量: " + receipt.getProductCount());

                // 设置产品信息
                if (receipt.getProductId() != null) {
                    Product product = productMapper.selectById(receipt.getProductId());
                    if (product != null) {
                        resp.setProductId(product.getProductId());
                        resp.setProductName(product.getProductName());
                        resp.setProductCode(product.getProductCode());
                        System.out.println("产品信息: " + product.getProductName() + " (" + product.getProductCode() + ")");
                    } else {
                        System.out.println("未找到产品ID: " + receipt.getProductId());
                    }
                } else {
                    System.out.println("收货单中产品ID为空");
                }
            } else {
                System.out.println("未找到收货单ID: " + d.getGoodsReceiptId());
            }
        } else {
            System.out.println("收货单ID为空，尝试从采购订单获取产品信息");
            
            // 当没有收货单时，尝试从采购订单获取产品信息
            if (d.getPurchaseOrderId() != null) {
                // 查询该采购订单相关的收货单，获取产品信息
                LambdaQueryWrapper<WarehouseReceipt> receiptWrapper = new LambdaQueryWrapper<>();
                receiptWrapper.eq(WarehouseReceipt::getOrderId, d.getPurchaseOrderId());
                List<WarehouseReceipt> receipts = warehouseReceiptMapper.selectList(receiptWrapper);
                
                if (!receipts.isEmpty()) {
                    WarehouseReceipt firstReceipt = receipts.get(0);
                    resp.setReceiptNo(firstReceipt.getReceiptNo());
                    resp.setReceiptTime(firstReceipt.getReceiptTime());
                    resp.setProductCount(firstReceipt.getProductCount());
                    System.out.println("从采购订单关联的收货单获取信息: " + firstReceipt.getReceiptNo());
                    
                    // 设置产品信息
                    if (firstReceipt.getProductId() != null) {
                        Product product = productMapper.selectById(firstReceipt.getProductId());
                        if (product != null) {
                            resp.setProductId(product.getProductId());
                            resp.setProductName(product.getProductName());
                            resp.setProductCode(product.getProductCode());
                            System.out.println("从收货单获取产品信息: " + product.getProductName() + " (" + product.getProductCode() + ")");
                        }
                    }
                } else {
                    System.out.println("采购订单没有关联的收货单");
                }
            }
        }

        System.out.println("构建完成，最终响应对象: " + resp);
        return resp;
    }
}




